package com.machinsight.library.dao;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * Copyright ©2017-2020 Machinsight Technology Co., Ltd.All rights reserved.
 * Author: Zhoushaohua
 * Date: 2020/1/2
 * Description:SQL数据库操作类
 */
public class SqlSessionController {
    private SqlSessionFactory mSqlSessionFactory = null;

    private SqlSessionController() {
        try {
            init();
        } catch (IOException e) {
            System.out.println("初始化SqlSessionFactory失败。");
        }
    }

    private static class Builder {
        private static final SqlSessionController INSTANCE = new SqlSessionController();
    }

    public static SqlSessionController getInstance() {
        return Builder.INSTANCE;
    }

    private void init() throws IOException {
        Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
        mSqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    }

    /**
     * 打开SQL会话，与closeSession组合使用，必须要形成闭合会路，一开一关
     *
     * @return SqlSession {@link SqlSession}
     * @throws IOException 抛出IO异常
     */
    public SqlSession openSession() throws IOException {
        if (mSqlSessionFactory == null) {
            init();
        }
        return mSqlSessionFactory.openSession();
    }

    /**
     * 关闭SQL会话，与openSession配合使用
     *
     * @param session SqlSession {@link SqlSession}
     */
    public void closeSession(SqlSession session) {
        if (session != null) {
            session.close();
        }
    }
}
